package com.diyunapp.xilinapp.me;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.ProvinceBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.City;
import com.diyunapp.xilinapp.utils.MyAsyncTask;
import com.diyunapp.xilinapp.utils.MyAsyncTask01;
import com.diyunapp.xilinapp.utils.MyAsyncTask02;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EditAddressActivity extends StatusBarFragmentActivity implements
        android.view.View.OnClickListener{

    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.shouhuo_name)
    EditText shouhuoName;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.shouhuo_phone_et)
    EditText shouhuoPhoneEt;
    @Bind(R.id.lin_address)
    LinearLayout lin_address;
    @Bind(R.id.province_et)
    EditText provinceEt;
    @Bind(R.id.street_et)
    EditText streetEt;
    @Bind(R.id.shewei_moren)
    ImageView sheweiMoren;

    @Bind(R.id.area_id)
    TextView area_id;
    @Bind(R.id.address_id)
    TextView address_id;
    @Bind(R.id.city_id)
    TextView city_id;
    @Bind(R.id.address_id1)
    TextView address_id1;
    @Bind(R.id.address_id2)
    TextView address_id2;
    private String name;
    private String phone;
    private String area_info;
    private String address;
    private String addressId;
    private List<ProvinceBean.DateBean> info = new ArrayList<>();
    private View chooseProvinceDialog;
    private ListView banksLv;
    private int item = 1;
    private int item_01 = 1;

    private AlertDialog.Builder builder = null;
    private LinearLayout login = null;
    private Dialog dialog;
    private Button button_01 = null;
    private List<City> list_city = null;
    private List<City> list_city01 = null;
    private List<City> list_city02 = null;
    private PopupMenu popupMenu = null;
    private Menu menu;;
    private int index = 0;
    private MyAsyncTask asyncTask;
    private boolean istrue = true;
    private String key;
    private int whitch1 = 9999;
    private int whitch2 = 9999;
    public String areaId;
    public String cityId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        View headView;
        headView = findViewById(R.id.addaddress_menubar_inc);
        super.MenuWidget(headView);
        addressId = getIntent().getExtras().getString("addressId");
        name = getIntent().getExtras().getString("name");
        phone = getIntent().getExtras().getString("phone");
        area_info = getIntent().getExtras().getString("area_info");
        address = getIntent().getExtras().getString("address");
        SharedPreferences userinfo=getSharedPreferences("user_info",MODE_PRIVATE);
        key=userinfo.getString("key","");
        title.setText("编辑地址");
        initDiaData();
        initView();
    }

    private void initDiaData() {
        provinceEt.setOnClickListener(onButtonClick);
        list_city = new ArrayList<City>();
        list_city01 = new ArrayList<City>();
        list_city02 = new ArrayList<City>();
//        requestQueue = Volley.newRequestQueue(getApplicationContext());
        asyncTask = new MyAsyncTask(list_city);

        MyAsyncTask02 asyncTask02 = new MyAsyncTask02(list_city02);


        asyncTask
                .execute("http://www.xilingou.com/mobile/index.php?act=goods&op=people_city");
    }

    private void initView() {
        shouhuoName.setText(name);
        shouhuoPhoneEt.setText(phone);
        provinceEt.setText(area_info);
        streetEt.setText(address);
    }

    public void EditAddress() {

        String true_name = toUtf8String(shouhuoName.getText().toString().trim());
        String area_info = toUtf8String(provinceEt.getText().toString().trim());
        String address = toUtf8String(streetEt.getText().toString().trim());
//        String true_name = shouhuoName.getText().toString().trim();
//        String area_info = provinceEt.getText().toString().trim();
//        String address = streetEt.getText().toString().trim();
        String tel_phone = shouhuoPhoneEt.getText().toString().trim();
        String area_id=areaId;
        String city_id=cityId;


        Log.i("zhangxiaoxidebug", "true_name=" + area_info);
//        toast(address_id.getText().toString().trim());
        String url = "http://www.xilingou.com/mobile/index.php?" +
                "act=member_address&op=address_edit&key="+MainActivity.myLogin.getLoginkey()+"&" +
                "address_id="+addressId+"&true_name="+true_name+"&area_id="+area_id+"&city_id="+city_id+"&" +
                "area_info="+area_info+"&address="+address+"&tel_phone="+tel_phone+"&mob_phone="+tel_phone+"";
//        toast(url);
        Log.i("zhangxiaoxidebug", "url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
                            if (result == 200) {
                                String datas=resultObject.getString("datas");

                                if(datas.equals("1")){
                                    toast("修改成功");
                                }else{
                                    JSONObject data = resultObject.optJSONObject("datas");
                                    String error=data.optString("error");
                                    toast(error);
                                }

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");
                    }
                });
    }

    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
    @OnClick({R.id.go_back, R.id.lin_address, R.id.sure_to_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back:
//                nextAct(AddressActivity.class);
                finish();
                break;
            case R.id.lin_address:

                break;
            case R.id.sure_to_add:
                if (shouhuoName.getText().toString().trim() == "") {
                    toast("收货人不能为空");
                } else if (shouhuoPhoneEt.getText().toString().trim() == "") {
                    toast("电话不能为空");
                } else if (provinceEt.getText().toString().trim() == "") {
                    toast("省市区不能为空");
                } else if (streetEt.getText().toString().trim() == "") {
                    toast("街道不能为空");
                } else {
                    EditAddress();

                }
                finish();
                break;

        }
    }
    private View.OnClickListener onButtonClick = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // TODO Auto-generated method stub

            login = (LinearLayout) View.inflate(EditAddressActivity.this,
                    R.layout.alertdialog, null);
            button_01 = (Button) login.findViewById(R.id.button1);


            for (int i = 0; i < 3; i++) {
                if (i == 0) {
                    ((RelativeLayout) (login.getChildAt(2)))
                            .setOnClickListener(onButtonClick1);
                } else {
                    ((RelativeLayout) (login.getChildAt(2 * i+2)))
                            .setOnClickListener(onButtonClick1);
                }
            }


            builder = new AlertDialog.Builder(EditAddressActivity.this);
            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
                    // TODO Auto-generated method stub
                    whitch1=9999;
                    whitch2=9999;
                    return false;
                }
            });
            builder.setCancelable(false);
            builder.setCancelable(true).setView(login);
//            builder.setTitle(
//                    "                      地区选择")
//                    .setCancelable(true).setView(login);
//            builder.create();
            dialog = builder.show();
        }
    };
    private View.OnClickListener onButtonClick1 = new View.OnClickListener() {

        public String index_01 = null;

        @Override
        public void onClick(View arg0) {

            // TODO Auto-generated method stub
            final int index = login.indexOfChild(arg0) / 2-1;
            // initOnClickListener(index);
            final TextView textview1 = (TextView) login
                    .findViewById(R.id.textView_shenfen);
            final TextView textview2 = (TextView) login
                    .findViewById(R.id.textView_scity);
            final TextView textview3 = (TextView) login
                    .findViewById(R.id.textView_quyu);
            final TextView textview4 = (TextView) login
                    .findViewById(R.id.textView_shenfen1);
            final TextView textview5 = (TextView) login
                    .findViewById(R.id.textView_scity1);
            final TextView textview6 = (TextView) login
                    .findViewById(R.id.textView_quyu1);
            final Button button_01 = (Button) login.findViewById(R.id.button1);
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    EditAddressActivity.this);
            int index_0;
            // 指定下拉列表的显示数据
            builder.setCancelable(true);
            if (index == 0) {
                String[] str = new String[list_city.size()];
                String[] cities = { "广州", "上海", "北京", "香港", "澳门" };
                for (int i = 0; i < list_city.size(); i++) {

                    str[i] = list_city.get(i).getArea_name().toString();
                }
                // 设置一个下拉的列表选择项
                builder.setItems(str, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (index == 0) {
                            textview1.setText(list_city.get(which)
                                    .getArea_name().toString());
                            textview4.setText(list_city.get(which).getArea_id().toString());
                            areaId=list_city.get(which).getArea_id().toString();
                            index_01 = list_city.get(which).getArea_id();
                            MyAsyncTask01 asyncTask01 = new MyAsyncTask01(list_city01);
                            asyncTask01
                                    .execute(""+MainActivity.url+"act=goods&op=city&area_id="
                                            +list_city.get(which).getArea_id());
                            whitch1 = which;
                            list_city01.clear();
                        }
                    }
                });
//                item = 0;
//                item_01 = 1;
                builder.show();
            }else if (index == 1) {
                if (whitch1 != 9999) {
                    String[] str = new String[list_city01.size()];

                    for (int i = 0; i < list_city01.size(); i++) {

                        str[i] = list_city01.get(i).getArea_name().toString();

                    }
                    // 设置一个下拉的列表选择项
                    builder.setItems(str, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {


                            textview2.setText(list_city01.get(which)
                                    .getArea_name().toString());
                            textview5.setText(list_city01.get(which).getArea_id().toString());
                            cityId=list_city01.get(which).getArea_id().toString();
                            index_01 = list_city01.get(which).getArea_id();
                            String ci= textview4.getText().toString().trim();
//                                toast(ci);
                            int ci1= Integer.parseInt(ci);
                            if(ci1==32||ci1==34||ci1==33) {
                                toast("无下属区域");
                                whitch2 = 9999;

                            }else {
                                MyAsyncTask02 asyncTask02 = new MyAsyncTask02(
                                        list_city02);

                                asyncTask02
                                        .execute("" + MainActivity.url + "act=goods&op=city&area_id="
                                                + list_city01.get(which)
                                                .getArea_id());


                                list_city02.clear();
                                whitch2 = which;
                            }}
                    });
//                    item = 1;
//                    item_01 = 0;
                    builder.show();
                }
                else {
                    Toast.makeText(getApplicationContext(), "请选择省份",
                            Toast.LENGTH_SHORT).show();
                }
            } else if (index == 2) {
                if (whitch2 != 9999) {
                    String[] str = new String[list_city02.size()];

                    for (int i = 0; i < list_city02.size(); i++) {

                        str[i] = list_city02.get(i).getArea_name().toString();
//                        item = 1;
                    }

                    // 设置一个下拉的列表选择项
                    builder.setItems(str, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            textview3.setText(list_city02.get(which)
                                    .getArea_name().toString());
                            textview6.setText(list_city02.get(which).getArea_id().toString());
//                            list_city02.clear();
//                            item = 0;
                        }
                    });
                    builder.show();
                } else {
                    Toast.makeText(getApplicationContext(), "请选择城市",
                            Toast.LENGTH_SHORT).show();
                }
            }
            button_01.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tx1=null;
                    if(textview1.getText().toString()=="请选择"||textview1.getText().toString().equals("请选择")){
                        tx1="";
                    }else{
                        tx1=textview1.getText().toString();
                    }
                    String tx2=null;
                    if(textview2.getText().toString()=="请选择"||textview2.getText().toString().equals("请选择")){
                        tx2="";
                    }else{
                        tx2=textview2.getText().toString();
                    }
                    String tx3=null;
                    if(textview3.getText().toString()=="请选择"||textview3.getText().toString().equals("请选择")){
                        tx3="";
                    }else{
                        tx3=textview3.getText().toString();
                    }
                    String area=tx1+""+tx2+""+tx3;
                    provinceEt.setText(area);
                    address_id.setText(textview4.getText().toString());
                    address_id1.setText(textview5.getText().toString());
                    address_id2.setText(textview6.getText().toString());

                    item = 1;
                    item_01 = 1;
                    dialog.dismiss();

//                        list_city.get(i).getArea_id();
                }
            });
        }

    };
    public String index_01;


}
